<template>
  <div style="width: 50%;margin: 10px auto">
    <div class="card">
      <div v-if="id === '' || id === null || id === undefined" style="text-align: center;font-size: 25px;margin-bottom: 20px">
        <el-page-header @back="deleteNoImg(form.id);$router.back()" content="发布商品"></el-page-header>
      </div>
      <div v-else style="text-align: center;font-size: 25px;margin-bottom: 20px">
        <el-page-header @back="deleteNoImg(form.id);$router.back()" content="编辑商品"></el-page-header>
      </div>
      <el-form :model="form" label-width="100px" style="padding-right: 50px" :rules="rules" ref="formRef">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="名称"></el-input>
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="form.category" placeholder="请选择分类">
            <el-option :value="item.name" v-for="item in categoryList" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="价格"></el-input>
        </el-form-item>
        <el-form-item label="图片" prop="img">
          <el-upload
              :action="$baseUrl + '/files/upload'"
              :headers="{ token: user.token }"
              list-type="picture"
              :on-success="handleImgSuccess"
              :limit="1"
              :on-exceed="handleExceed"
          >
            <el-button type="primary">上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="发货地址" prop="address">
          <el-input v-model="form.address" placeholder="发货地址"></el-input>
        </el-form-item>
        <el-form-item label="上架状态" prop="saleStatus">
          <el-radio-group v-model="form.saleStatus">
            <el-radio label="上架"></el-radio>
            <el-radio label="下架"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="详情" prop="content">
          <div id="editor"></div>
        </el-form-item>
      </el-form>
      <el-button type="primary" style="width: 30%;margin: 20px auto" @click="save">确认发布</el-button>
    </div>
  </div>
</template>

<script>
const imgUri =[];
const beforeImgUri =[];
const afterImgUri =[];
import E from "wangeditor"
export default {
  name: "AddGoods",
  data() {
    return {
      id: this.$route.query.id,
      user: JSON.parse(localStorage.getItem('xm-user')),
      form: {
        saleStatus: '上架',
      },  // 表单数据
      categoryList:[],
      editor: null, // 富文本编辑器
      rules: {  // 校验规则
        name: [{required: true, message: '请输入名称', trigger: 'blur'}],
        price: [{required: true, message: '请输入价格', trigger: 'blur'},
          {validator: (rule, value, callback) => {
            // 判断是否是整数或者小数
            if (!/^[1-9]\d*(\.\d{1,2})?$/.test(value)) {
              callback(new Error('请输入正确的价格'))
            }
            else {
              callback()
            }
          }, trigger: 'blur'
        }],
        address: [{required: true, message: '请输入发货地址', trigger: 'blur'}],
        saleStatus: [{required: true, message: '请输入上架状态', trigger: 'blur'}],
      }
    }
  },
  created() {
    this.loadCategory();
    this.loadGoods();
    imgUri.push(this.getFileName(this.form.img));
  },
  methods: {
    handleExceed(files, fileList) {
      this.$message.warning('只能上传一张图片!');
    },
    setRichText(html) {
      this.$nextTick(() => {
        this.editor = new E(`#editor`)
        this.editor.config.uploadImgServer = this.$baseUrl + '/files/editor/upload'
        this.editor.config.uploadFileName = 'file'
        this.editor.config.uploadImgHeaders = {
          token: this.user.token
        }
        this.editor.config.uploadImgParams = {
          type: 'img',
        }
        this.editor.config.zIndex = 0
        this.editor.create()  // 创建
        this.editor.txt.html(html)
      })
    },

    loadCategory() {
      this.$request.get('/category/selectAll').then(res => {
        if (res.code === '200') {
          this.categoryList = res.data || [];
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    loadGoods(){
      if(this.id){
        this.$request.get("/goods/selectById/"+this.id).then(res => {
          this.form = res.data || {};
          this.setRichText(this.form.content);
          //将this.getImgSrc(this.form.content)赋值给fwbImgUri
          beforeImgUri.push(...this.getImgSrc(this.form.content))
          console.log(beforeImgUri)
        })
      }
      else{
        this.setRichText('');
        console.log(this.getImgSrc(this.form.content));
      }
    },
    handleAdd() {   // 新增数据
      this.form = {}  // 新增数据的时候清空数据
      this.setRichText('')
    },
    save() {   // 保存按钮触发的逻辑  它会触发新增或者更新
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.form.content = this.editor.txt.html();  // 获取富文本编辑器的内容
          console.log(imgUri)
          this.deleteImg();
          this.$request({
            url: this.form.id ? '/goods/update' : '/goods/add',
            method: this.form.id ? 'PUT' : 'POST',
            data: this.form
          }).then(res => {
            if (res.code === '200') {  // 表示成功保存
              this.handleAdd();  // 清空数据
              this.$message.success('发布成功')
              if(this.id === '' || this.id === null || this.id === undefined) {
                this.$router.push("/front/home")
              }
              else{
                this.$router.push("/front/frontGoods")
              }
            } else {
              this.$message.error(res.msg)  // 弹出错误的信息
            }
          })
        }
      })
    },
    handleImgSuccess(response, file, fileList) {
      this.form.img = response.data;
      let fileName = response.data.substring(response.data.lastIndexOf('/') + 1)
      imgUri.push(fileName)
      console.log(imgUri)
    },
    handleFwbImgSuccess(response, file, fileList) {
      let fileName = response.data.substring(response.data.lastIndexOf('/') + 1)
      afterImgUri.push(fileName)
      console.log(afterImgUri)
    },
    deleteImg(){
      console.log(imgUri)
      if(imgUri.length > 1) {
        imgUri.pop();
        console.log(imgUri)
        this.$request.delete('/files/delete/batch', {data: imgUri})
      }
      //   清空imgUri
      imgUri.length = 0
    },
    deleteNoImg(id){
      if(id !== void 0){
        imgUri.splice(0, 1);
      }
      console.log(imgUri)
      this.$request.delete('/files/delete/batch', {data: imgUri})
      //   清空imgUri
      imgUri.length = 0
    },
    getFileName(filePath){
      return filePath?.substring(filePath.lastIndexOf('/') + 1)
    },
    //根据文本返回所有img标签的src属性的值
    getImgSrc(content) {
      const imgReg = /<img.*?(?:>|\/>)/gi;
      const srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
      if(!content) return [];
      const arr = content.match(imgReg);
      const srcArr = [];
      if(arr === null) return [];
      for (let i = 0; i < arr.length; i++) {
        const src = arr[i].match(srcReg);
        srcArr.push(src[1]);
      }
      return srcArr;
    },
    deleteFwbImg(imgUri){
      this.$request.delete('/files/delete/batch', {data: imgUri})
    }
  }
}
</script>

<style scoped>
.card {
  /* 背景颜色 */
  background-color: #fff;

  /* 边框样式 */
  border: 1px solid #e0e0e0;

  /* 圆角 */
  border-radius: 8px;

  /* 盒子阴影效果 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  /* 内边距 */
  padding: 20px;

  /* 外边距 */
  margin: 20px 0;

  /* 宽度设置，可以根据实际情况调整 */
  width: 100%;
  max-width: 800px;

  /* 确保内容垂直居中 */
  display: flex;
  flex-direction: column;
  justify-content: center;
}
</style>